import React from 'react';
import {Link} from 'react-router-dom';
import {ImagePicker, InputItem, List, Modal, Tag, TextareaItem, Toast} from 'antd-mobile';
import Icon from '@components/icon';
import Preview from '@container/preview';
import {fetch} from '@utils/Fetch';

const prompt = Modal.prompt;
const alert = Modal.alert;

class Add extends React.PureComponent {
  constructor(props) {
    super(props);
    const query = props.location.state || {};
    this._id = query._id || '';
    this.state = {
      form: {},
      loading: false,
      regions: [],
      regionChange: !this._id,
      files: [],
      previewVisible: false,
      preview: null
    }
  }

  componentDidMount() {
    this.fLoad();
  }

  fLoad = () => {
    if (!this._id) {
      return false;
    }
    const url = `/api/case/one?_id=${this._id}`;
    fetch(url).get()
      .success(res => {
        const {regions, ...form} = res.content || {};
        const files = [];
        if (form.huxing) {
          files.push({
            id: form._id,
            _id: form._id,
            url: form.huxing
          });
        }
        this.setState({regions, form, files});
      });
  };
  fChange = (value) => {
    const form = Object.assign({}, this.state.form, value);
    this.setState({form});
  };
  fSubmit = async () => {
    const {history} = this.props;
    const {form, regionChange, regions, files} = this.state;
    if (regionChange) {
      form.regions = regions;
    }
    if (files.length > 0) {
      const file = files[0];
      if (file.file) {
        const formData = new FormData();
        formData.append('file', file.file);
        const result = await fetch(`/api/file?bucket=mh`).upload(formData);
        form.huxing = result.content.url;
      }
    }

    function success(res) {
      Toast.success(res.message, 1);
      history.replace('/home');
    }

    if (this._id) {
      fetch('/api/case').put(form).success(success);
    } else {
      fetch('/api/case').post(form).success(success);
    }
  };
  fAlert = () => {
    const btns = [
      {text: '取消'},
      {text: '删除', onPress: this.fDelete}
    ];
    alert('删除案例', '确定删除？', btns);
  };
  fDelete = () => {
    const {history} = this.props;
    fetch(`/api/case?_id=${this._id}`).delete()
      .success(res => {
        res.message && Toast.success(res.message, 1);
        history.replace('/home');
      });
  };
  fAdd = () => {
    const self = this;
    const regions = this.state.regions;
    prompt('新增区域', '',
      [
        {text: '取消'},
        {
          text: '确定',
          onPress: value => {
            self.setState({regions: regions.concat([value]), regionChange: true});
          }
        },
      ], 'default', null, ['区域名称']);
  };
  fClose = () => {
    if (!this.state.regionChange) {
      this.setState({regionChange: true});
    }
  };
  fSelect = (files) => {
    let form = this.state.form;
    if (files.length === 0) {
      form = Object.assign({}, form, {huxing: ''});
    }
    this.setState({files, form});
  };
  fImageClick = (index, files) => {
    const file = files[index];
    if (file) {
      this.setState({preview: {url: file.url, _id: file._id}, previewVisible: true});
    }
  };
  fHidden = () => {
    this.setState({preview: null, previewVisible: false});
  };

  render() {
    const {loading, regions = [], form, files, previewVisible, preview} = this.state;
    return (
      <div className='home-add fixed-full'>
        <div className='home-add-header'>
          <div><Link to='/home' replace><Icon type='home' /></Link></div>
          {!this._id ? null : <div style={{color: '#ff4d4f'}} onClick={this.fAlert}>删除</div>}
          <div onClick={this.fSubmit}>保存</div>
        </div>
        <List className='content'>
          <InputItem labelNumber={2}
                     value={form.title || ''}
                     onChange={(v) => this.fChange({title: v})}
          >案例</InputItem>
          <TextareaItem title='备注'
                        autoHeight
                        value={form.comment || ''}
                        labelNumber={2}
                        onChange={(v) => this.fChange({comment: v})}
                        rows={2} />
          <List.Item wrap>
            区域
            <div className='home-add-region'>
              {regions.map((r, i) => (
                <Tag key={i} closable onClose={this.fClose}>{r}</Tag>
              ))}
              <Tag onChange={this.fAdd}>➕</Tag>
            </div>
          </List.Item>
          <List.Item wrap>
            <ImagePicker
              files={files}
              onChange={this.fSelect}
              selectable={files.length < 1}
              accept='image/gif,image/jpeg,image/jpg,image/png'
              onImageClick={this.fImageClick}
            />
          </List.Item>
        </List>
        {preview && previewVisible ? (
          <Preview visible={previewVisible}
                   onClose={this.fHidden}
                   isLazy={!!preview._id}
                   url={preview.url}
          />
        ) : null}
      </div>
    )
  }
}

export default Add;
